import { BASE_URL } from "../../utils/config";

Page({
  data: {
    showCamera: false,
    isRegistered: false,
  },

  onLoad() {
    // 检查是否已注册人脸
    this.checkFaceRegistration();
  },

  // 检查人脸注册状态
  async checkFaceRegistration() {
    try {
      // TODO: 调用后端API检查人脸注册状态
      const isRegistered = false;
      this.setData({ isRegistered });
    } catch (error) {
      console.error('检查人脸注册状态失败:', error);
      wx.showToast({
        title: '检查注册状态失败',
        icon: 'error'
      });
    }
  },

  // 显示/隐藏相机
  handleShowCamera() {
    if (this.data.isRegistered) {
      wx.showToast({
        title: '您已完成注册',
        icon: 'success'
      });
      return;
    }
    this.setData({
      showCamera: true
    });
  },

  // 拍照
  async takePhoto() {
    const camera = wx.createCameraContext();
    camera.takePhoto({
      quality: 'high',
      success: async (res) => {
        try {
          // TODO: 调用后端API上传人脸照片
          await this.uploadFacePhoto(res.tempImagePath);
          this.setData({
            showCamera: false,
            isRegistered: true
          });
          wx.showToast({
            title: '注册成功',
            icon: 'success'
          });
        } catch (error) {
          console.error('上传人脸照片失败:', error);
          wx.showToast({
            title: '注册失败',
            icon: 'error'
          });
        }
      },
      fail: (error) => {
        console.error('拍照失败:', error);
        wx.showToast({
          title: '拍照失败',
          icon: 'error'
        });
      }
    });
  },

  // 取消拍照
  cancelPhoto() {
    this.setData({
      showCamera: false
    });
  },

  // 上传人脸照片
  async uploadFacePhoto(tempFilePath: string) {
    // TODO: 实现上传人脸照片到后端的逻辑
    const fileResult = await new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${BASE_URL}/file/upload`,
        filePath: tempFilePath,
        name: 'file',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail: reject
      });
    });
    // 修改用户信息
    const token = wx.getStorageSync('token');
    const { data } = JSON.parse(fileResult);
    wx.request({
      url: `${BASE_URL}/student/bindFace`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: {
        faceImage: data.url
      },
      success: () => {
        wx.showToast({
          title: '头像更新成功',
          icon:'success'
        });
      }
    })
  },

  // 相机错误处理
  error(e: any) {
    console.error('相机错误:', e.detail);
    wx.showToast({
      title: '相机启动失败',
      icon: 'error'
    });
  }
});